import apiClient from './api';

export interface ExcelFile {
  id: string;
  name: string;
  size: number;
  type: string;
  uploadTime: string;
}

export interface ExcelAskRequest {
  sessionId: string;
  fileId: string;
  question: string;
  sheet?: string;
  columns?: string[];
  filters?: Record<string, any>;
}

export interface ExcelUploadResponse {
  success: boolean;
  file_id: string;
  fileId?: string;
  file_name?: string;
  fileName?: string;
  message?: string;
}

export interface ExcelAskResponse {
  success: boolean;
  answer: string;
  preview?: string;
  metadata?: Record<string, any>;
  file_id?: string;
  fileId?: string;
  file_name?: string;
  fileName?: string;
}

export interface ExcelDataset {
  id: string;
  name: string;
  filename?: string;
  created_at?: string;
  rows?: number;
  cols?: number;
}

export interface ExcelPreview {
  columns: string[];
  rows: any[][];
}

export interface ExcelChartResponse {
  option: any;
}

class ExcelService {
  /**
   * 上传Excel文件
   * @param file 文件对象
   * @param sessionId 会话ID
   * @returns 文件ID
   */
  async uploadFile(file: File, sessionId: string): Promise<ExcelUploadResponse> {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('session_id', sessionId);

      const response = await apiClient.post<ExcelUploadResponse>('/v1/excel/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });

      return response.data;
    } catch (error) {
      console.error('上传Excel文件失败:', error);
      throw error;
    }
  }

  /**
   * 向Excel文件提问
   * @param request 提问请求参数
   * @returns 回答和预览
   */
  async askExcel(request: ExcelAskRequest): Promise<ExcelAskResponse> {
    try {
      const payload: Record<string, unknown> = {
        session_id: request.sessionId,
        file_id: request.fileId,
        question: request.question
      };
      if (request.sheet) {
        payload.sheet = request.sheet;
      }
      if (request.columns && request.columns.length > 0) {
        payload.columns = request.columns;
      }
      if (request.filters && Object.keys(request.filters).length > 0) {
        payload.filters = request.filters;
      }

      const response = await apiClient.post<ExcelAskResponse>('/v1/excel/ask', payload, {
        timeout: 120000 // Excel 问答可能较慢，给予更长超时时间
      });
      return response.data;
    } catch (error) {
      console.error('Excel提问失败:', error);
      throw error;
    }
  }

  /**
   * 清除Excel文件
   * @param sessionId 会话ID
   * @returns 操作结果
   */
  async clearExcel(sessionId: string): Promise<{ success: boolean }> {
    try {
      const response = await apiClient.delete<{ success: boolean }>('/v1/excel/clear', {
        params: { session_id: sessionId }
      });
      return response.data;
    } catch (error) {
      console.error('清除Excel文件失败:', error);
      throw error;
    }
  }

  async uploadDataset(file: File): Promise<ExcelDataset> {
    const formData = new FormData();
    formData.append('file', file);
    const response = await apiClient.post('/v1/excel/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    return response.data;
  }

  async listDatasets(params?: { page?: number; size?: number }): Promise<{ items: ExcelDataset[]; total: number }> {
    const response = await apiClient.get('/v1/excel/datasets', {
      params: {
        page: params?.page ?? 1,
        size: params?.size ?? 50
      }
    });
    return response.data;
  }

  async previewDataset(datasetId: string, limit = 50): Promise<ExcelPreview> {
    const response = await apiClient.get(`/v1/excel/datasets/${datasetId}/preview`, { params: { limit } });
    return response.data;
  }

  async askDataset(datasetId: string, question: string): Promise<{ answer: string }> {
    const response = await apiClient.post(`/v1/excel/datasets/${datasetId}/qa`, { question });
    return response.data;
  }

  async chartDataset(datasetId: string, payload: { chart_type: string; x_field: string; y_field: string; group_field?: string }): Promise<ExcelChartResponse> {
    const response = await apiClient.post(`/v1/excel/datasets/${datasetId}/chart`, payload);
    return response.data;
  }
}

export default new ExcelService();
